// pages/fighting/fighting.js
var util = require('../../utils/util.js')
var http = require('../../utils/http.js')

const app = getApp();
var audio = wx.createInnerAudioContext();
// 在页面中定义激励视频广告
let videoAd = null

Page({

  /**
   * 页面的初始数据
   */
  data: {
    tagNormal: false,
    closeTag: false,
    isClock: false,
    background: '',
    boxShadow: '',
    audio_active: true,
    money: '',
    pkMoney: 0,
    AIpkMoney: 0,
    noteNum:'',
    index:'',
    chat: '',
    emo: [],
    chatShow: NaN,
    emoShow: NaN,
    countDown: '',
    redList: ['/images/people-future.png',
              '/images/people-future.png',
              '/images/people-future.png',
              '/images/people-future.png',
              '/images/people-future.png',
              // '/images/people-red.png'
              // '/images/people-miss.png'
            ],
    AIredList:['/images/people-future.png',
              '/images/people-future.png',
              '/images/people-future.png',
              '/images/people-future.png',
              '/images/people-future.png',
              // '/images/people-red.png'
              // '/images/people-miss.png'
            ],
    emoList: ['奥利给','我太难了','有内味了','爱了爱了','就这？','神仙打架'],
    songTitle: ['第一题','第二题','第三题','第四题','第五题'],
    th: -1,
    emoSrcList: [
      {
        txt: '我蒙的',
        src: '/images/smile_cry.png'
      },
      {
        txt: '小姐姐',
        src: '/images/touch_heart.png'
      },
      {
        txt: '兄弟',
        src: '/images/mer_per.png'
      }
    ],
    songList: [],
    control: false,
    isAnimation: true,
    rightProgress: 1,
    leftProgress: 1,
    emoBox: false,
    maskShow: false,
    redShow: NaN,
    robotMask: false,
    robot: NaN,
    maskSettle: false,
    maskWin: false,
    firstToast: false,
    threeToast: false,
    normalGet: NaN,
    normalGetMusicTag: 0,
    doubleGet: true,
    fourToast: false,
    allGet: true,
  },
  countTimer: '',
  sendTxtTimer: '',
  sendEmoTimer: '',

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var th = that.data.th;
    if( th == 4) {
      audio.pause();
    }
    // 在页面onLoad回调事件中创建激励视频广告实例
    if (wx.createRewardedVideoAd) {
      videoAd = wx.createRewardedVideoAd({
        adUnitId: 'adunit-9e7297304053444f'
      })
      videoAd.onLoad(() => {})
      videoAd.onError((err) => {})
      videoAd.onClose((res) => {
        if (res && res.isEnded || res === undefined) {
          console.log("我看完视频了");
        } else {
          // 播放中途退出，进行提示
          wx.showToast({
            title: '观看广告时间不足，无法获得奖励',
            icon: "none",
            duration: 2000
          })
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    var money = app.globalData.money;
    var userNoteNum = wx.getStorageSync('noteNum');
    var haveWinNum = wx.getStorageSync('totalNum');
    var loginName = wx.getStorageSync('loginName');
    var touxiang = wx.getStorageSync('touxiang');
    var aiPkPlayer = wx.getStorageSync('aiPkPlayer');
    var realName = aiPkPlayer.realName;
    var AIMoney = aiPkPlayer.money;
    var userLogo = aiPkPlayer.userLogo;
    that.getSongList();
    that.setData({
      userNoteNum,
      haveWinNum,
      money,
      loginName,
      touxiang,
      realName,
      AIMoney,
      userLogo,
    })
    that.autoEnd();
    var th = that.data.th;
    if( th == 4) {
      audio.pause();
    }
  },
  // 获取歌曲 芋泥一起布丁
  getSongList: function() {
    var that = this;
    var th = that.data.th;
    var question = wx.getStorageSync('question');
    util.log(question);
    audio.loop = true;
    audio.autoplay = true;
    audio.src = question.title;
    audio.onPlay( () => {
      util.log('开始播放')
    });
    audio.onError( (res) => {
      util.log(res.errMsg);
      util.log(res.errCode);
    })
    if(question) {
      var songList = JSON.parse(question.answerContent).arr;
      th++;
      that.setData({
        rightProgress: 1,
        leftProgress: 1,
        songList,
        th,
        isClock: false,
      })
    }
  },
  back:function () {
    wx.showModal({
      content: '确定返回吗？',
      success (res) {
        if (res.confirm) {
          wx.navigateBack({
            delta: 1000
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  // 选择歌曲
  choose:function(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var th = that.data.th;
    that.setData({
      isClock: true,
      rightProgress: 0,
      leftProgress: 0,
    })
    clearInterval(that.countTimer);
    that.autoEnd();
    that.clickNextSong(index);
    if( th == 4) {
      audio.pause();
    }
  },
  // 点击下一题
  clickNextSong: function(index) {
    var that = this;
    var AIpkMoney = that.data.AIpkMoney;
    var redList = that.data.redList;
    var AIredList = that.data.AIredList;
    var songList = that.data.songList;
    var th = that.data.th;
    if(th == 4) {
      that.clickEnd();
    }
    var resultId = wx.getStorageSync('resultId')
    var correctOption = ['A','B','C','D','E']
    const data = {
      resultId: resultId,
      correctOption: correctOption[index]
    }
    if(resultId) {
      http.pkAnswer(data).then( (res) => {
        songList[index].selected = true;
        if( res.isTrue == 1) {
          redList[th] = '/images/people-red.png';
          AIredList[th] = '/images/people-miss.png';
          var pkMoney = that.data.pkMoney;
          pkMoney = parseFloat((pkMoney + res.pkMoney/10000).toFixed(3));
          var playerRed =  res.pkMoney / 10000 ;
          // 答对颜色rgba(56, 197, 32,1)':答错颜色'#e9394f'
          //答对boxShadow '0rpx -10rpx 0rpx 0rpx #339b0a inset'    答错 '0rpx -10rpx 0rpx 0rpx #b61559 inset'
         that.setData({
           playerRed,
           pkMoney,
           AIredList,
           songList,
           redList,
           maskShow: true,
           redShow: true,
           background: 'rgba(56, 197, 32,1)',
           boxShadow: '0rpx -10rpx 0rpx 0rpx #339b0a inset' 
         })
         var closeToastTimer = setInterval(() =>{
             that.setData({
               maskShow:  false,
               redShow: 'false'
             })
             clearInterval(closeToastTimer);
         },400)
       } else {
         redList[th] = '/images/people-miss.png';
         AIredList[th] = '/images/people-red.png';
         AIpkMoney = parseFloat((AIpkMoney + res.pkMoney/10000).toFixed(3));
         var AIRed = res.pkMoney / 10000 ;
         that.setData({
           AIRed,
           AIpkMoney,
           redList,
           AIredList,
           robotMask: true,
           robot: true,
           songList,
           background: '#e9394f',
           boxShadow: '0rpx -10rpx 0rpx 0rpx #b61559 inset' 
         })
         var closeToastTimer = setInterval(() =>{
          that.setData({
            robotMask:  false,
            robot: 'false'
          })
          clearInterval(closeToastTimer);
      },400)
       }
          wx.setStorageSync('question', res.question);
          wx.setStorageSync('resultId', res.resultId);
          if(!res.question) {
            // var pkMoney = parseFloat((that.data.pkMoney + res.pkMoney/10000).toFixed(3));
            var winNum = res.winNum;
            if( winNum > 2) {
              var noteNum = 3;
            } else {
              var noteNum = 1;
            }
            util.log(winNum);
            util.log(noteNum);
            that.setData({
              // pkMoney,
              noteNum
            })
          }
          if( th < 4) {
            setTimeout( () => {
              that.getSongList();
            },1000)
          }
      })
    }

  },
  // 自动下一题
  nextSong: function(index) {
    var that = this;
    var AIpkMoney = that.data.AIpkMoney;
    var redList = that.data.redList;
    var AIredList = that.data.AIredList;
    var resultId = wx.getStorageSync('resultId');
    var correctOption = ['A','B','C','D','E'];
    const data = {
      resultId: resultId,
      correctOption: correctOption[index]
    }
    if(resultId) {
      http.pkAnswer(data).then( (res) => {
        var th = that.data.th;
        if( res.isTrue == 1) {

        } 
        else {
         redList[th] = '/images/people-miss.png';
         AIredList[th] = '/images/people-red.png';
         AIpkMoney = parseFloat((AIpkMoney + res.pkMoney/10000).toFixed(3));
         var AIRed = res.pkMoney / 10000 ;
         that.setData({
           redList,
           AIredList,
           robotMask: true,
           robot: true,
           AIRed,
           AIpkMoney
         })
         var closeToastTimer = setInterval(() =>{
          that.setData({
            robotMask:  false,
            robot: 'false'
          })
          clearInterval(closeToastTimer);
      },400)
       }
          wx.setStorageSync('question', res.question)
          wx.setStorageSync('resultId', res.resultId)
          that.setData({
            isClock: false
          })
          that.getSongList();
          if(!res.question) {
            var th = that.data.th;
            th++;
            var pkMoney = Math.floor(res.pkMoney/10000*100)/100;
            var winNum = res.winNum;
            if( winNum > 2) {
              var noteNum = 3;
            } else {
              var noteNum = 1;
            }
            util.log(winNum);
            util.log(noteNum);
            that.setData({
              th,
              pkMoney,
              noteNum
            })
          }
      })
    }


  },
  // 点击结束
  clickEnd: function() {
    var that = this;
    var th = that.data.th;
    if( th == 4) {
      clearInterval(that.countTimer);
      audio.pause();
      var countDown = 0;
      that.setData({
        countDown,
        isAnimation: false,
        rightProgress: 0,
        leftProgress: 0,
        control: true
      })
      setTimeout( () => {
        wx.showLoading({
          title: '正在结算中......',
        })
      },1000)
      setTimeout(function () {
        wx.hideLoading();
        that.firstToast();
        console.log('结算弹窗');
      }, 1500)
      }
  },
  // 自动结束
  autoEnd: function() {
    var that = this;
    clearInterval(that.countTimer);
    var countDown = 12;
    // that.setData({
    //   rightProgress: 1,
    //   leftProgress: 1,
    // })
    var countTimer = setInterval( () => {
      countDown--;
      if(countDown == 0) {
        countDown = 12;
        var th = that.data.th;
        console.log('自动结束：',th)
        if( th < 4) {
          that.nextSong(4);
        } else {
            audio.pause();
            countDown = 0;
            that.setData({
              countDown,
              isAnimation: false,
              rightProgress: 0,
              leftProgress: 0,
              control: true
            })
            wx.showLoading({
              title: '正在结算中......',
            })
            setTimeout(function () {
              wx.hideLoading();
              that.firstToast();
            }, 1000)
            clearInterval(countTimer)
        }
      }
      that.setData({
        countDown,
      })
    },1000)
    that.countTimer = countTimer;
  },
  // 第一个弹窗
  firstToast: function() {
    var that = this;
    that.setData({
      maskSettle: true,
      firstToast: true,
    })
    setTimeout(() => {
      that.setData({
        normalGet: true,
      })
    },1500)
  },
  // 普通领取后,显示关闭按钮
  normalGet: function() {
    var that = this;
    that.setData({
      normalGet: false,
      allGet: false,
    })
  },
  // 全场领取后,显示关闭按钮
  getAll: function() {
    var that = this;
    // 用户触发广告后，显示激励视频广告
    if (videoAd) {
      videoAd.show().catch(() => {
        // 失败重试
        videoAd.load()
          .then(() => videoAd.show())
          .catch(err => {
            console.log('激励视频 广告显示失败')
          })
      })
    }

    this.setData({
      allGet: false,
      normalGet: false,
    })
  },
  // 点击关闭后弹出获得音符的奖励
  clickClose: function() {
    var that = this;
    that.setData({
      firstToast: false,
      threeToast: true,
    })
    setTimeout(() => {
      that.setData({
        tagNormal: true,
      })
    },800)
  },
  // 双倍领取
  doubleGet: function() {
    var that = this;
    that.setData({
      doubleGet: false,
      tagNormal: false,
      closeTag: true,
    })

    if (wx.createRewardedVideoAd) {
      videoAd = wx.createRewardedVideoAd({
        adUnitId: 'adunit-96e23d22adce41d3'
      })
      videoAd.onLoad(() => { })
      videoAd.onError((err) => { })
      videoAd.onClose((res) => { 
        if (res && res.isEnded || res === undefined) {
          console.log("我看完视频了");
          // 调用翻倍接口6
          that.zeroOrOne(1);
        } else {
          // 播放中途退出，进行提示
          wx.showToast({
            title: '观看广告时间不足，无法获得奖励',
            icon: "none",
            duration: 2000
          })
        }

      })
    }

    // 用户触发广告后，显示激励视频广告
    if (videoAd) {
      videoAd.show().catch(() => {
        // 失败重试
        videoAd.load()
          .then(() => videoAd.show())
          .catch(err => {
            console.log('激励视频 广告显示失败')
          })
      })
    }
  },
  // 普通领取音符
  normalGetMusicTag: function() {
    var that = this;
    that.setData({
      tagNormal: false,
      doubleGet: false,
    })
    setTimeout( () => {
      that.setData({
        closeTag: true,
      })
    },1500)
    that.zeroOrOne(0)
  },
  // 普通领取音符还是全场领取音符
  zeroOrOne: function(isGet) {
    var that = this;
    const data = {
      isGet: isGet
    }
    http.pkReward(data).then( res => {
      var noteNum = res.noteNum;
      that.setData({
        noteNum,
      })
    })
  },
  // 关闭音符领取
  closeMusicTag: function() {
    var that = this;
    var noteNum = that.data.noteNum;
    // var userNoteNum = noteNum + userNoteNum;
    that.setData({
      threeToast: false,
      maskSettle: false,
    })
    setTimeout(() => {
      
      that.setData({
        maskWin: true,
        fourToast: true,
        // userNoteNum,
      })
    if( noteNum == 3) {
      var haveWinNum = that.data.haveWinNum + 1;
      that.setData({
        haveWinNum,
      })
      //播放胜利音效
      audio.loop = false;
      audio.autoplay = true;
      audio.src = '/mp3/win.mp3';
      audio.onPlay( () => {
      util.log('开始播放')
  });
      audio.onError( (res) => {
      util.log(res.errMsg);
      util.log(res.errCode);
  })
    } else {
      //播放失败音效
      audio.loop = false;
      audio.autoplay = true;
      audio.src = '/mp3/defeat.mp3';
      audio.onPlay( () => {
      util.log('开始播放')
      });
      audio.onError( (res) => {
      util.log(res.errMsg);
      util.log(res.errCode);
      })
    }
    
    },500)
  },
  // 播放暂停
  change_music: function() {
    var that = this;
    var audio_active = that.data.audio_active;
    if(audio_active) {
      audio.pause();
      that.setData({
        audio_active: false,
      })
    } else {
      audio.play();
      that.setData({
        audio_active: true,
      })
    }
    var control = that.data.control === true ? false:true;
    var isAnimation = that.data.isAnimation === true ? false:true;
    that.setData({
      control,
      isAnimation,
    })
  },
  // 开启表情
  emoControl: function() {
    var that = this;
    var emoBox = that.data.emoBox === true? false:true;
    that.setData({
      emoBox,
    })
  },
  // 关闭表情
  emoChange: function() {
    var that = this;
    that.setData({
      emoBox: false,
    })
  },
  // 发文字
  sendTxt: function(e) {
    var that = this;
    var emoList = that.data.emoList;
    var chat = e.currentTarget.dataset.item;
    that.setData({
      chat,
      chatShow: true,
      emoShow: NaN,
    })
    var AIsendTxt = setTimeout( () => {
      var AIrandom = Math.floor(Math.random()*5);
      var chat =emoList[AIrandom];
      that.setData({
        chat,
        chatShowAI: true,
        emoShowAI: NaN,
      })
    },4000)
    setTimeout( () => {
      that.setData({
        chatShowAI: 'false',
      })
    },6000)
    var sendTxtTimer = setInterval(() => {
      that.setData({
        chatShow: 'false',
      })
      clearInterval(sendTxtTimer);
    },2000)
    that.sendTxtTimer = sendTxtTimer;
  },
  // 发文字加表情
  sendEmo: function(e) {
    var that = this;
    var emo = e.currentTarget.dataset.item;
    that.setData({
      emo,
      emoShow: true,
      chatShow: NaN,
    })
    var sendEmoTimer = setInterval(() => {
      that.setData({
        emoShow: 'false',
      })
      clearInterval(sendEmoTimer);
    },2000)
    that.sendEmoTimer = sendEmoTimer;
  },
  // 回到首页
  returnIndex: function() {
    wx.navigateBack({
      delta: 1000
    })
  },
  // 再来一局
  fightAgainst: function() {
    http.clickPK().then( (res) => {
      wx.navigateTo({
        url: '/pages/matching/matching'
      })
      console.log('进入匹配页面')
  }) 
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    var that = this;
    clearInterval(that.sendTxtTimer);
    clearInterval(that.sendEmoTimer);
    clearInterval(that.countTimer);
    audio.pause();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var that = this;
    clearInterval(that.sendTxtTimer);
    clearInterval(that.sendEmoTimer);
    clearInterval(that.countTimer);
    audio.pause();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})